package org.demo.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * 资源授权配置服务
 * 
 * @author garca
 *
 */
@Component
@Slf4j
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

    /**
     * 每一个资源所需要的角色 Collection<ConfigAttribute>决策器会用到
     */
    private static HashMap<String, Collection<ConfigAttribute>> map = null;
    static {
    	map=new HashMap<>();
    	ConfigAttribute admin = new SecurityConfig("admin");
    	ConfigAttribute user = new SecurityConfig("user");
    	map.put("/user/admin",Arrays.asList(admin) );
    	map.put("/user/common",Arrays.asList(user) );
    }

    /**
     * 根据请求获取资源授权配置
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //object 中包含用户请求的request 信息
        final HttpServletRequest request = ((FilterInvocation) o).getHttpRequest();
        Optional<Entry<String, Collection<ConfigAttribute>>> matcher=map.entrySet().parallelStream().filter(entry->{
        	return new AntPathRequestMatcher(entry.getKey()).matches(request);
        }).findFirst();
        if(matcher.isPresent()) {
        	return matcher.get().getValue();
        }
        return new ArrayList<>();
    }
    
    

    /**
     * 获取通用的资源授权配置
     */
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
    	log.info("获取通用的资源授权配置");
        return new ArrayList<>();
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
